<script setup lang="ts">
import formButton from '@renderer/components/formButton.vue'
import NavBar from '@renderer/components/navBar.vue'
import SelectExportMode from '@renderer/components/selectExportMode.vue'
import useCompute from '@renderer/composables/useCompute'
import useComputeForm from '@renderer/composables/useComputeForm'
import helper from '@renderer/utils/helper'
import { ElMessage } from 'element-plus'
import { computed, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
const route = useRouter()
const pageQuery = route.currentRoute.value.query
const MainMaterialsData = ref<MainMaterialsList[]>([])
const initSubmitForm = () => ({
  cate_name: '',
  print_name: '',
  name: '',
  value: '',
  unit: '',
  main_materials: '',
  labour: '',
  auxiliary_material: '',
  remark: '',
  unit_price: '',
})
const submitForm = reactive(initSubmitForm())
const addDataDialog = ref(false)
const selectTemplateDialog = ref(false)
const totalPrice = ref(0)
const changeRow = ref<any[]>([])
const total = computed(() => {
  return ((submitForm.unit_price as any) * 1 * ((submitForm.value as any) * 1)).toFixed(2)
})
const handleClose = async () => {
  Object.assign(submitForm, initSubmitForm())
  addDataDialog.value = false
  await initData()
}
const handleAddData = async () => {
  if (changeRow.value.length) {
    await handleSaveTableData(changeRow.value, 25)
    changeRow.value = []
  }
  addDataDialog.value = true
}
const handleSave = async () => {
  if (!submitForm.name) {
    ElMessage.error('项目代号不能为空')
    return
  }
  if (!submitForm.print_name) {
    ElMessage.error('项目名称不能为空')
    return
  }
  if (!submitForm.unit) {
    ElMessage.error('单位不能为空')
    return
  }
  if (!submitForm.unit_price) {
    ElMessage.error('单价不能为空')
    return
  }
  if (!submitForm.value) {
    ElMessage.error('数量不能为空')
    return
  }
  await addBudgetData({
    calculate_id: pageQuery.calculate_id,
    type_name: '主材预算',
    cate_name: '其他',
    print_name: submitForm.print_name,
    name: submitForm.name,
    unit: submitForm.unit,
    unit_price: submitForm.unit_price,
    main_materials: submitForm.main_materials,
    labour: submitForm.labour,
    auxiliary_material: submitForm.auxiliary_material,
    remark: submitForm.remark,
    value: submitForm.value,
  })
  handleClose()
}
const initData = async () => {
  await getCalculateDetail({ calculate_id: pageQuery.calculate_id })
  if (calculateInfo.value?.check_gather == 2 || !checkRule('预算明细查看权')) {
    ElMessage({ type: 'error', message: '抱歉！您没有此权限' })
    return
  }
  MainMaterialsData.value = []
  const res: MainMaterialsModel[] = await getMainMaterialsList({
    calculate_id: pageQuery.calculate_id,
    type_name: '主材预算',
    client_type: 'GUI',
  })
  totalPrice.value = 0
  res.forEach((item: MainMaterialsModel) => {
    if (item.list) {
      item.list.forEach((itemChild: MainMaterialsList, childIndex: number) => {
        MainMaterialsData.value.push({
          ...itemChild,
          pinlei_name: item.cate_name ? item.cate_name.replace(/#/g, '\n') : '其他',
          index: childIndex,
          itemListLength: item.list.length,
        })
      })
    } else {
      MainMaterialsData.value.push({
        name: '',
        pinlei_name: item.cate_name,
        price: item.total_price + '',
        index: 0,
        itemListLength: 1,
      })
    }
    totalPrice.value += item.total_price
  })
  await getCalculateTableSet({ type: 3 })
}
const handleExport = async () => {
  selectTemplateDialog.value = true
}
const handleSaveMode = async (event) => {
  handleCloseMode()
  const res = await exportMainTable({
    calculate_id: pageQuery.calculate_id,
    mode: event.mode,
  })
  downLoadFile(res, '主材预算明细表.xlsx')
}
const handleCloseMode = () => {
  selectTemplateDialog.value = false
}
const handleBlueCompute = (newVal: MainMaterialsList, isCompute: boolean = false) => {
  if (isCompute) {
    const childIndex = MainMaterialsData.value?.findIndex((item) => item.name == newVal.name)
    if (childIndex != -1) {
      MainMaterialsData.value![childIndex!].price = (Number(newVal.value) * Number(newVal.unit_price)).toFixed(2) + ''
      const totalIndex = MainMaterialsData.value?.findIndex((item) => item.name == '总计')
      if (totalIndex != -1) {
        MainMaterialsData.value![totalIndex!].price = '0'
        MainMaterialsData.value!.forEach((item) => {
          if (item.name != '总计') {
            MainMaterialsData.value![totalIndex!].price =
              (Number(MainMaterialsData.value![totalIndex!].price) + Number(item.price)).toFixed(2) + ''
          }
        })
      }
    }
  }
  if (!changeRow.value.includes(newVal)) {
    changeRow.value.push(newVal)
  } else {
    changeRow.value = changeRow.value.filter((item) => item !== newVal)
    changeRow.value.push(newVal)
  }
}
const handleSaveData = async () => {
  if (!changeRow.value.length) {
    ElMessage({ type: 'success', message: '保存成功！' })
    return
  }
  await handleSaveTableData(changeRow.value, 25)
  await initData()
  changeRow.value = []
}
const currentHandleType = ref('')
const currentFindIndex = ref(-1)
const isAllIsExit = ref(false)
const isAllIndex = ref(0)
const handleFindReplace = () => {
  currentFindIndex.value = -1
  currentHandleType.value = ''
  window.api.openWindow('findSearch', {
    title: '备注查找与替换',
    currentWindowName: 'basiceQuipment',
    currentPage: 'mainMaterials',
  })
}
const handleFind = (content: string) => {
  const includesList = MainMaterialsData.value!.map((item, index) =>
    (item.remark && item.remark.includes(content)) || (item.print_name && item.print_name.includes(content))
      ? index
      : -1,
  ).filter((index) => index !== -1)
  if (!includesList.length) {
    ElMessage({ type: 'error', message: '抱歉！您的查找内容不存在！' })
    currentFindIndex.value = -1
    return
  }
  if (currentFindIndex.value == -1) {
    currentFindIndex.value = includesList[0]
  } else {
    const currentFind = includesList.findIndex((item) => item === currentFindIndex.value)
    if (currentFind == includesList.length - 1) {
      currentFindIndex.value = includesList[0]
    } else {
      currentFindIndex.value = includesList[currentFind + 1]
    }
  }
  let remarkIsExit = MainMaterialsData.value![currentFindIndex.value].remark!.includes(content)
  let printNameIsExit = MainMaterialsData.value![currentFindIndex.value].print_name!.includes(content)
  if (remarkIsExit && printNameIsExit && !isAllIsExit.value) {
    if (isAllIndex.value == 0) {
      blueInput('name')
      const currentFind = includesList.findIndex((item) => item === currentFindIndex.value - 1)
      if (currentFind == includesList.length - 1) {
        currentFindIndex.value = includesList[0]
      } else {
        currentFindIndex.value = includesList[currentFind]
      }
      isAllIndex.value = 1
    } else {
      blueInput('remark')
      isAllIndex.value = 0
      isAllIsExit.value = false
    }
  } else if (remarkIsExit && !printNameIsExit) {
    blueInput('remark')
  } else {
    blueInput('name')
  }
}
const handleAllFind = (content: string) => {
  const result = MainMaterialsData.value!.filter(
    (item) => (item.remark && item.remark.includes(content)) || (item.print_name && item.print_name.includes(content)),
  )
  if (!result.length) {
    ElMessage({ type: 'error', message: '抱歉！您的查找内容不存在！' })
    currentFindIndex.value = -1
    window.api.sendListArray(JSON.stringify([]))
    return
  }
  window.api.sendListArray(JSON.stringify(result))
}
window.api.acceptSendMsg((handleType, currentPage, content, replaceContent, ids) => {
  if (currentPage == 'mainMaterials') {
    switch (handleType) {
      case 'handleFind':
        if (currentHandleType.value == 'handleAllFind') {
          currentFindIndex.value = -1
        }
        handleFind(content)
        break
      case 'handleAllFind':
        currentFindIndex.value = -1
        handleAllFind(content)
        break
      case 'handleReplace':
      case 'handleAllReplace':
        if (ids) {
          let selectIdList = ids.split(',')
          selectIdList.forEach((idItem) => {
            const index = MainMaterialsData.value!.findIndex((item) => item.id == Number(idItem))
            handlePlaceRemark(
              index,
              MainMaterialsData.value![index].remark,
              MainMaterialsData.value![index].print_name,
              content,
              replaceContent,
            )
          })
        } else {
          if (currentFindIndex.value == -1) {
            ElMessage({ type: 'error', message: '抱歉！未找到匹配的数据！' })
            return
          }
          handlePlaceRemark(
            currentFindIndex.value,
            MainMaterialsData.value![currentFindIndex.value].remark,
            MainMaterialsData.value![currentFindIndex.value].print_name,
            content,
            replaceContent,
          )
          currentFindIndex.value = -1
        }
        break
    }
    currentHandleType.value = handleType
  }
})
const handlePlaceRemark = (index, checkRemarkContent, checkNameContent, content, replaceContent) => {
  if (checkRemarkContent.includes(content) && !checkNameContent.includes(content)) {
    MainMaterialsData.value![index].remark = MainMaterialsData.value![index].remark!.replace(content, replaceContent!)
  } else if (!checkRemarkContent.includes(content) && checkNameContent.includes(content)) {
    MainMaterialsData.value![index].print_name = MainMaterialsData.value![index].print_name!.replace(
      content,
      replaceContent!,
    )
  } else {
    MainMaterialsData.value![index].remark = MainMaterialsData.value![index].remark!.replace(content, replaceContent!)
    MainMaterialsData.value![index].print_name = MainMaterialsData.value![index].print_name!.replace(
      content,
      replaceContent!,
    )
  }
  handleBlueCompute(MainMaterialsData.value![index])
}
const blueInput = (type: 'remark' | 'name') => {
  let handleRef = `${type}Input${MainMaterialsData.value![currentFindIndex.value].id}`
  const handleRefDom = document.getElementById(handleRef)
  if (handleRefDom) handleRefDom.focus()
}
const { getMainMaterialsList, addBudgetData, exportMainTable } = useCompute()
const { downLoadFile, handleSaveTableData, checkRule } = helper()
const { getCalculateTableSet, calculateSetInfo, calculateInfo, getCalculateDetail, updateMainBudgetCate } =
  useComputeForm()
await initData()
interface SpanMethodProps {
  row: MainMaterialsList
  columnIndex: number
}
const objectSpanMethod = ({ row, columnIndex }: SpanMethodProps) => {
  if (columnIndex === 0) {
    if (row.index == 0) {
      return { rowspan: row.itemListLength, colspan: 1 }
    } else {
      return { rowspan: 0, colspan: 0 }
    }
  } else {
    return
  }
}
const handleBlueRemark = async (remark: string, id: string) => {
  let replaceRemark = remark.replace(/\n/g, '#')
  await updateMainBudgetCate({
    calculate_id: pageQuery.calculate_id,
    cate_name: replaceRemark,
    id,
  })
}
const remarkStyle = (itemCount: number) => {
  if (itemCount) {
    return {
      height: `${remarkHeight.value * itemCount}px`,
    }
  } else {
    return
  }
}
const remarkHeight = ref(0)
const observer = new MutationObserver(() => {
  const elements = document.getElementsByClassName('el-table__cell')
  if (elements.length > 0) {
    const firstElement = elements[9]
    remarkHeight.value = firstElement.clientHeight
    observer.disconnect()
  }
})
observer.observe(document.body, { childList: true, subtree: true })
</script>

<template>
  <main class="bg-white flex flex-col" style="height: -webkit-fill-available">
    <div class="flex flex-1 justify-center" v-if="calculateInfo?.check_gather == 2 || !checkRule('预算明细查看权')">
      <el-empty
        image="https://cw3.obs.cn-north-4.myhuaweicloud.com/api/uploads/images/b1ed1d14709b890118b4c2b3da9114b351e11b9d.png"
        description="抱歉！您没有此权限" />
    </div>
    <section v-else class="flex flex-col overflow-hidden">
      <div class="px-6 h-[50px] border-b flex items-center bg-white" style="width: -webkit-fill-available">
        <div class="flex gap-3">
          <formButton @click="handleAddData" v-if="checkRule('预算明细修改权')">添加项目</formButton>
          <formButton @click="handleSaveData" v-if="checkRule('预算明细修改权')">保存数据</formButton>
          <formButton @click="handleExport">导出</formButton>
          <formButton @click="handleFindReplace" v-if="checkRule('预算明细修改权')">查找替换</formButton>
        </div>
      </div>
      <div class="flex flex-col gap-3 p-6 pt-4 overflow-y-auto flex-1">
        <div class="flex flex-col">
          <div class="text-center font-bold text-2xl text-black mt-3 mb-1">{{ calculateSetInfo?.title }}</div>
          <div class="text-center text-sm text-[#888888]">工程地址：{{ pageQuery.calculate_name }}</div>
        </div>
        <div class="flex flex-col gap-3">
          <el-table
            :data="MainMaterialsData"
            border
            header-align="center"
            :span-method="objectSpanMethod"
            :header-cell-style="{ background: '#FFF4E5', fontSize: '14px', color: '#888', fontWeight: '400' }">
            <el-table-column prop="pinlei_name" label="产品品类" align="center" width="250">
              <template #default="scope">
                <el-input
                  v-if="checkRule('预算明细修改权') && scope.row.pinlei_name != '总计'"
                  v-model="scope.row.pinlei_name"
                  type="textarea"
                  :input-style="remarkStyle(scope.row.itemListLength)"
                  @change="handleBlueRemark(scope.row.pinlei_name, scope.row.id)" />
              </template>
            </el-table-column>
            <el-table-column prop="name" label="项目代号" align="center" width="130" />
            <el-table-column prop="print_name" label="项目名称" align="center" width="130">
              <template #default="scope">
                <el-input
                  v-model="scope.row.print_name"
                  :id="`nameInput${scope.row.id}`"
                  v-if="scope.row.pinlei_name != '总计' && checkRule('预算明细修改权')"
                  @input="handleBlueCompute(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column prop="unit_price" label="单价" align="center" width="100">
              <template #default="scope">
                <el-input
                  v-model="scope.row.unit_price"
                  v-if="scope.row.pinlei_name != '总计' && checkRule('预算明细修改权')"
                  type="number"
                  @mousewheel.native.prevent
                  @input="handleBlueCompute(scope.row, true)" />
              </template>
            </el-table-column>
            <el-table-column prop="value" label="数量" align="center" width="92">
              <template #default="scope">
                <el-input
                  v-model="scope.row.value"
                  v-if="scope.row.pinlei_name != '总计' && checkRule('预算明细修改权')"
                  type="number"
                  @mousewheel.native.prevent
                  @input="handleBlueCompute(scope.row, true)" />
              </template>
            </el-table-column>
            <el-table-column prop="unit" label="单位" align="center" width="80">
              <template #default="scope">
                <el-input
                  v-model="scope.row.unit"
                  v-if="scope.row.pinlei_name != '总计' && checkRule('预算明细修改权')"
                  @input="handleBlueCompute(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column prop="price" label="合计" align="center" width="100" />
            <el-table-column prop="remark" label="备注" align="center">
              <template #default="scope">
                <el-input
                  v-if="scope.row.pinlei_name != '总计' && checkRule('预算明细修改权')"
                  v-model="scope.row.remark"
                  :id="`remarkInput${scope.row.id}`"
                  @input="handleBlueCompute(scope.row)" />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </section>
    <el-dialog v-model="addDataDialog" width="500" align-center :show-close="false" style="padding: 0">
      <div class="flex flex-col pb-4">
        <NavBar @handleClose="handleClose" title="新增项目数据" />
        <el-form :model="submitForm" class="px-6 pt-6 flex flex-col gap-6" label-width="90">
          <el-form-item label="项目代号:" required>
            <el-input v-model="submitForm.name" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="项目名称:" required>
            <el-input v-model="submitForm.print_name" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="单位:" required>
            <el-input v-model="submitForm.unit" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="数量:" required>
            <el-input
              v-model="submitForm.value"
              placeholder="请输入"
              clearable
              type="number"
              @mousewheel.native.prevent />
          </el-form-item>
          <el-form-item label="单价:" required>
            <el-input
              v-model="submitForm.unit_price"
              placeholder="请输入"
              clearable
              type="number"
              @mousewheel.native.prevent />
          </el-form-item>
          <el-form-item label="合计:" required>
            <el-input v-model="total" placeholder="请输入" clearable disabled />
          </el-form-item>
          <el-form-item label="备注:">
            <el-input v-model="submitForm.remark" placeholder="请输入" clearable />
          </el-form-item>
          <div class="flex justify-center" @click="handleSave">
            <div class="save-button">提交</div>
          </div>
        </el-form>
      </div>
    </el-dialog>
    <SelectExportMode
      :selectTemplateDialog="selectTemplateDialog"
      openCate="主材预算导出模板"
      @handleSaveMode="handleSaveMode"
      @handleCloseMode="handleCloseMode" />
  </main>
</template>

<style lang="scss" scoped>
.el-form {
  display: flex;
}
.el-form-item {
  margin-bottom: 0px;
  margin-right: 20px !important;
  flex: 1;
}
::v-deep .el-dialog__header {
  padding-bottom: 0 !important;
}
.save-button {
  @apply text-white px-16 py-3 rounded-md cursor-pointer;
  background: linear-gradient(142deg, #ff9600 0%, #ffb242 100%);
}
</style>
